//
// Created by wk on 2024/1/2.
//

#include "EncryptDes.h"
#include <stdio.h>
#include <string>
#include <stdlib.h>
EncryptDes::EncryptDes() {
    mEncryptType = EncryptType_MPEG;

    memset(&mEncDes, 0, sizeof(mEncDes));
}

EncryptDes::~EncryptDes() {

}

static int un_des(unsigned char *data, int size, DES_key_schedule *key, unsigned char *out, int sizeout) {
    int i = 0;
    int offer = 0;
    char *outbuff = (char *) malloc(sizeout);
    for (i = 0; (size - i) >= 8; i += 8) {
        DES_ecb_encrypt((const_DES_cblock*)&data[i], (DES_cblock *)&outbuff[offer], key, DES_DECRYPT);
        offer += 8;
    }
    if ((offer > 0) && (offer < 8)) {
        char buff[8];
        char buff_out[8];
        memset(buff, 0, sizeof(buff));
        memcpy(buff, &data[offer], size);
        DES_ecb_encrypt((const_DES_cblock*)buff, (DES_cblock*)buff_out, key, DES_DECRYPT);
        memcpy(&outbuff[offer], buff_out, sizeout);
    }
    memcpy(out, outbuff, sizeout);
    free(outbuff);
}

bool EncryptDes::isEncryptType(FILE *inputFile) {

    char b[128 * 1024] = {0};
    char key[16] = {0};
    fseek(inputFile, 0, SEEK_SET);
    memset(&b, 0, sizeof(b));

    int ret = fread(b, 1, sizeof(b), inputFile);
    if (ret != sizeof(b)) {
        return false;
    }

    sprintf((char *) key, "%08x", *(off32_u *) b);

    DES_set_key_unchecked((const_DES_cblock*)key, &mEncDes.des);

    un_des((unsigned char *)(b + 4), EKTV_ENCRYPT_HEADER, (DES_key_schedule*)&mEncDes.des, (unsigned char*)(b + 4), EKTV_ENCRYPT_HEADER);

    if (*(off32_u *) (b + 4) != EKTV_FLAGS) {
        return false;
    }
    return true;
}
